<template>
  <div class="app-container hk-flex-column">
    <search-form
      :data="queryParams"
      :field-list="fieldList"
      :list-type-info="dictList"
      :is-asset="true"
      style="padding-bottom: 0rem"
      @handleSearch="handleQuery"
      @handleReset="resetQuery">
      <template #filter-assetTypes>
        <div class="ca-select clearfix">
          <el-select
            ref="selectIt"
            v-model="assetValue"
            :options="citiesList"
            style="width: 220px"
            class="fake"
            multiple
            @change="clearSelect"
            @focus="selectFocus">
            <el-option v-for="item in citiesList" :key="item.id" :label="item.dictValue" :value="item.id" />
          </el-select>
          <el-cascader
            ref="cascader"
            v-model="queryParams.assetTypes"
            filterable
            :options="dictList.typeList"
            :props="assetProps"
            :show-all-levels="false"
            clearable
            style="width: 220px"
            class="test"
            :collapse-tags="false"
            @expand-change="expandChange"
            @change="handleChange($event, 'cascader')" />
        </div>
      </template>
    </search-form>

    <hk-table
      :table-data="tableData"
      :table-columns="tableList"
      :selection="false"
      :show-index="true"
      :total="total"
      :loading="loading"
      :table-height="80"
      operate
      :operate-width="100"
      :query-params="queryParams"
      @changePage="getDataList">
      <!-- 操作权限 -->
      <template #assetName="scope">
        <el-button style="font-size: 14px;" size="mini" type="text" @click="toDetail(scope.row)">{{ scope.row.assetName }}</el-button>
      </template>
      <template #assetCode="scope">
        <el-button style="font-size: 14px;" size="mini" type="text" @click="toDetail(scope.row)">{{ scope.row.assetCode }}</el-button>
      </template>
      <template #operate="scope">
        <el-button size="mini" type="text" @click="handleRecord(scope.row)">详情</el-button>
      </template>
    </hk-table>
    <RecordDrawer ref="record_drawer" />
  </div>
</template>
  
<script>
import { pageList, getDict, dictItemsList } from '@/api/specialProject/assetRecords'
import SearchForm from '@/components/HkSearchform/index.vue'
import HkTable from '@/components/Hk-Table/index.vue'
import RecordDrawer from './components/recordDrawer.vue'

export default {
  components: {
    SearchForm,
    HkTable,
    RecordDrawer,
  },
  beforeRouteLeave(to, from, next) {
    console.log(to, '路由')
    if (to.path === '/specialProject/assets/assetLibraryDetail') {
      const condition = JSON.stringify(this.queryParams)
      sessionStorage.setItem('condition', condition)
    } else {
      sessionStorage.removeItem('condition')
    }
    next()
  },
  beforeRouteEnter(to, from, next) {
    console.log(to, '路由')
    if (from.path !== '/specialProject/assets/assetLibraryDetail') {
      sessionStorage.removeItem('condition')
    }
    next()
  },
  data() {
    return {
      assetProps: {
        children: 'children',
        label: 'dictValue',
        value: 'id',
        emitPath: false,
        multiple: true,
      },
      queryParams: {
        current: 1,
        size: 10,
      },
      checkedList: [],
      ids: [],
      tableData: [],
      total: 0,
      loading: false,
      tableList: [
        { label: '设备名称', param: 'assetName', type: 'slot' },
        { label: '设备编号', param: 'assetCode', type: 'slot' },
        { label: '设备类型', param: 'assetType' },
        { label: '变更类型', param: 'changeType', width: '100px' },
        { label: '变更内容', param: 'changeContent' },
        { label: '操作人', param: 'userName' },
        { label: '操作时间', param: 'operationTime' },
      ],
      // 搜索框
      fieldList: [
        {
          label: '关键字',
          type: 'input',
          field: 'keyword',
          maxlength: 20,
          width: '258px',
          placeholder: '请输入设备名称、编号、变更关键字',
        },
        {
          label: '设备类型',
          type: 'slot',
          field: 'assetTypes',
          list: 'typeList',
          width: '220px',
        },
        {
          label: '变更类型',
          type: 'select',
          field: 'changeType',
          maxlength: 20,
          list: 'changeTypeList',
          width: '150px',
        },
        {
          label: '变更时间',
          type: 'dateRange',
          field: 'time',
          TimePickerOptions: {
            shortcuts: [
              {
                text: '最近一周',
                onClick(picker) {
                  // const end = new Date()
                  // const start = new Date()
                  const start = new Date(new Date().setHours(0, 0, 0, 0))
                  const end = new Date(new Date().setHours(23, 59, 59, 999))
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                  picker.$emit('pick', [start, end])
                },
              },
              {
                text: '最近一个月',
                onClick(picker) {
                  const start = new Date(new Date().setHours(0, 0, 0, 0))
                  const end = new Date(new Date().setHours(23, 59, 59, 999))
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                  picker.$emit('pick', [start, end])
                },
              },
              {
                text: '最近三个月',
                onClick(picker) {
                  const start = new Date(new Date().setHours(0, 0, 0, 0))
                  const end = new Date(new Date().setHours(23, 59, 59, 999))
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                  picker.$emit('pick', [start, end])
                },
              },
            ],
          },
          width: '150px',
        },
      ],
      citiesList: [],
      assetValue: [],
      nodeList: [],
      resArr: [],
      dictList: {
        typeList: [],
        changeTypeList: [],
      },
    }
  },
  created() {
    var cd = sessionStorage.getItem('condition')
    if (cd) {
      var condition = JSON.parse(cd)
      this.queryParams = condition
    }
  },
  mounted() {
    this.getDataList()
    this.getDictDatas()
  },
  methods: {
    toDetail(row) {
      console.log(row)
      this.$router.push({
        path: '/specialProject/assets/assetLibraryDetail',
        query: {
          id: row.assetId,
          title: '详情',
          dictValue: row.dictItems.dictValue,
          dictKey: row.dictItems.dictKey,
          dictId: row.dictItems.id,
        },
      })
    },
    async clearSelect(e) {
      const result = this.nodeList.filter((item) => e.includes(item.value))
      if (!result) {
        this.assetValue = []
        this.citiesList = []
        this.queryParams.assetTypes = []
      } else {
        this.nodeList = result
        const idArr = []
        this.citiesList = []
        for (let i = 0; i < result.length; i++) {
          idArr.push(result[i].value)
          this.citiesList.push(result[i].data)
        }
        this.assetValue = idArr
        this.resArr = []
        await this.getNodeId(result)
        this.queryParams.assetTypes = this.resArr
      }
    },
    getNodeId(array) {
      for (var item of array) {
        this.resArr.push(item.value)
        if (item.children.length > 0) {
          this.getNodeId(item.children)
        }
      }
    },
    selectFocus() {
      var that = this
      this.$refs.selectIt.blur()
      var timer = setInterval(() => {
        that.$refs.cascader.toggleDropDownVisible(true)
        clearInterval(timer)
      }, 200)
    },
    // 级联框
    handleChange(e, item) {
      if (!e) {
        this.assetValue = []
        this.citiesList = []
      } else {
        let nodeList = this.$refs[item].getCheckedNodes()
        // 如果三级全选就显示二级的，没有全选就显示三级的
        nodeList = nodeList.filter((option) => !(option.parent && option.parent.checked))
        this.nodeList = nodeList
        const idArr = []
        this.citiesList = []
        for (let i = 0; i < nodeList.length; i++) {
          idArr.push(nodeList[i].value)
          this.citiesList.push(nodeList[i].data)
        }
        this.assetValue = idArr
      }
    },
    // 解决级联选死机问题
    expandChange() {
      this.$nextTick(() => {
        // 添加这段代码
        const $el = document.querySelectorAll('.el-cascader-panel .el-cascader-node[aria-owns]')
        Array.from($el).map((item) => item.removeAttribute('aria-owns'))
      })
    },
    handleRecord(row) {
      this.$refs.record_drawer.show(row.id)
    },
    //  查询
    handleQuery() {
      this.queryParams.current = 1
      this.getDataList()
    },
    //  重置
    resetQuery() {
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.assetValue = []
      this.citiesList = []
      this.getDataList()
    },

    getDataList(val) {
      this.loading = true
      console.log(this.queryParams, 'this.queryParams')
      if (this.queryParams.time) {
        this.queryParams.startTime = this.queryParams.time[0]
        this.queryParams.endTime = this.queryParams.time[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
      if (this.queryParams.assetTypes) {
        this.queryParams.assetTypes = this.queryParams.assetTypes.toString()
      }

      pageList(this.queryParams).then((res) => {
        res.list.forEach((element) => {
          for (const key in element) {
            element[key] = element[key] || '—'
          }
        })
        this.loading = false
        this.tableData = res.list
        this.total = res.total
        const condition = JSON.stringify(this.queryParams)
        sessionStorage.setItem('condition', condition)
      })
    },
    // 字典获取
    getDictDatas() {
      // 类型
      getDict({ code: 'assetChangeLogType' }).then((res) => {
        this.dictList.changeTypeList = res.map((o) => {
          o.label = o.dictValue
          o.value = o.dictKey
          return o
        })
      })

      dictItemsList({ parentId: 0 }).then((res) => {
        this.dictList.typeList = res
      })
    },
  },
}
</script>
  
    <style lang="scss" scoped>
.ca-select {
  width: 220px;
  min-height: 32px;
  cursor: pointer;
  .fake {
    float: left;
    z-index: 9;
  }
  .test {
    float: left;
    visibility: hidden;
    width: 0px;
    height: 0px;
    z-index: -1;
  }
}
.el-row {
  position: absolute;
  right: 20px;
  top: 50px;
}
.total-title {
  margin-bottom: 15px;
  margin-top: 6px;
  line-height: 24px;
}
.font-size16 {
  font-size: 16px;
}
.flex-1 {
  flex: 1;
  justify-content: space-between;
  height: 100%;
}
.font-c-blue {
  color: #4b6eef;
  font-size: 36px;
}
.mt-20 {
  margin-top: 20px;
}
::v-deep {
  .content {
    padding-bottom: 0;
  }
}
</style>
  
  